<template>
  <div class="app-container">
    <!-- 表单 -->
    <el-form label-position="right" label-width="120px" :model="readerForm" :rules="rules">
      <!-- 数据源 -->
      <el-form-item label="数据库源：" prop="datasourceId">
        <el-select v-model="readerForm.datasourceId" filterable style="width: 300px" @change="rDsChange">
          <el-option
            v-for="item in rDsList"
            :key="item.id"
            :label="item.datasourceName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <!-- Schema -->
      <el-form-item v-show="dataSource==='postgresql' || dataSource==='oracle' ||dataSource==='sqlserver'" label="Schema：" prop="tableSchema">
        <el-select v-model="readerForm.tableSchema" allow-create default-first-option filterable style="width: 300px" @change="schemaChange">
          <el-option
            v-for="item in schemaList"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <!-- 解析方式 -->
      <el-form-item label="解析方式：">
        <el-select v-model="readerForm.parseType" style="width: 300px" @change="parseTypeChange">
          <el-option label="表名解析" value="table" />
          <el-option label="SQL语句" value="sql" />
          <el-option label="存储过程" value="procedure" />
        </el-select>
      </el-form-item>
      <el-form-item v-if="readerForm.parseType === 'table'" label="模糊匹配表名：">
        <el-input v-model="readerForm.fuzzyMatchingTableName" placeholder="请输入表名关键字" style="width: 300px" @change="fuzzyMatchingTable" />
      </el-form-item>
      <el-form-item v-if="readerForm.parseType === 'table'" label="数据库表名：" prop="tableName">
        <el-select v-model="readerForm.tableName" allow-create default-first-option filterable style="width: 300px" @change="rTbChange">
          <el-option v-for="item in rTbList" :key="item" :label="item" :value="item" />
        </el-select>
      </el-form-item>
      <el-form-item v-if="readerForm.parseType === 'sql'" label="SQL语句：" prop="querySql">
        <el-input v-model="readerForm.querySql" :autosize="{ minRows: 3, maxRows: 20}" type="textarea" placeholder="sql查询，一般用于多表关联查询时才用" style="width: 42%" />
        <el-button type="primary" @click.prevent="getColumns('reader')">解析字段</el-button>
      </el-form-item>
      <el-form-item v-if="readerForm.parseType === 'procedure'" label="存储过程语句：">
        <el-input v-model="readerForm.procedureCall" placeholder="exec 存储过程名 参数1,参数2" style="width: 300px" />
        <el-button type="primary" @click.prevent="getProcedureColumns">解析字段</el-button>
      </el-form-item>
      <el-form-item label="自定义表名：" prop="customTableName">
        <el-input v-model="readerForm.customTableName" placeholder="请输入目标表名" style="width: 300px" />
      </el-form-item>
      <el-form-item label="表注释：">
        <el-input v-model="readerForm.tableComment" placeholder="请输入表注释" style="width: 300px" />
      </el-form-item>
      <el-form-item label="设置表标签：">
        <el-select v-model="readerForm.isSetTag" style="width: 300px;">
          <el-option label="是" :value="true" />
          <el-option label="否" :value="false" />
        </el-select>
      </el-form-item>
      <el-form-item v-if="readerForm.isSetTag" label="表标签：">
        <el-checkbox-group v-model="readerForm.selectedTags" style="display: inline-block;">
          <el-checkbox
            v-for="tag in tagList"
            :key="tag.tagId"
            :label="tag.tagId"
          >
            {{ tag.tagName }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>

      <el-form-item v-if="rColumnList && rColumnList.length > 0" label="表所有字段：">
        <el-table
          ref="multipleTable"
          :data="rColumnList"
          border
          style="width: 100%;"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="columnName" label="字段名" min-width="150">
            <template slot-scope="{ row }">
              <span>{{ row.columnName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="字段描述" min-width="200">
            <template slot-scope="{ row }">
              <el-input v-model="row.columnDes" placeholder="请输入字段描述" />
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import * as dsQueryApi from '@/api/metadata-query'
import { list as jdbcDsList } from '@/api/datax-jdbcDatasource'
import Bus from '../busReader'

export default {
  name: 'RDBMSReader',
  data() {
    return {
      jdbcDsQuery: {
        current: 1,
        size: 200,
        ascs: 'datasource_name'
      },
      rDsList: [],
      rTbList: [],
      schemaList: [],
      rColumnList: [],
      loading: false,
      active: 1,
      customFields: '',
      customType: '',
      customValue: '',
      dataSource: '',
      tagList: [],
      readerForm: {
        datasourceId: undefined,
        tableName: '',
        columns: [],
        columnsType: [],
        where: '',
        querySql: '',
        checkAll: false,
        isIndeterminate: true,
        splitPk: '',
        tableSchema: '',
        fuzzyMatchingTableName: '',
        parseType: 'table',
        procedureCall: '',
        customTableName: '',
        tableComment: '',
        isSetTag: true,
        selectedTags: []
      },
      rules: {
        datasourceId: [{ required: true, message: 'this is required', trigger: 'change' }],
        tableName: [{ required: true, message: 'this is required', trigger: 'change' }],
        columns: [{ required: true, message: 'this is required', trigger: 'change' }],
        customTableName: [{ required: true, message: '请输入表名', trigger: 'blur' }]
      }
    }
  },
  watch: {
    'readerForm.datasourceId': function(oldVal, newVal) {
      if (this.dataSource === 'postgresql' || this.dataSource === 'oracle' || this.dataSource === 'sqlserver') {
        this.getSchema()
      } else {
        this.getTables('rdbmsReader')
      }
    },
    'readerForm.isSetTag': function(newValue) {
      if (!newValue) {
        this.readerForm.selectedTags = []
      }
    }
  },
  created() {
    this.getJdbcDs()
    this.getTagList()
  },
  methods: {
    handleSelectionChange(val) {
      this.selectedColumns = val
      this.readerForm.columns = val.map(item => item.columnName)
    },
    // 获取可用数据源
    getJdbcDs(type) {
      this.loading = true
      jdbcDsList(this.jdbcDsQuery).then(response => {
        const { records } = response
        this.rDsList = records
        this.loading = false
      })
    },
    // 获取表名
    getTables(type) {
      if (type === 'rdbmsReader') {
        let obj = {}
        if (this.dataSource === 'postgresql' || this.dataSource === 'oracle' || this.dataSource === 'sqlserver') {
          obj = {
            datasourceId: this.readerForm.datasourceId,
            tableSchema: this.readerForm.tableSchema,
            fuzzyMatchingTableName: this.readerForm.fuzzyMatchingTableName
          }
        } else {
          obj = {
            datasourceId: this.readerForm.datasourceId
          }
        }
        // 组装
        dsQueryApi.getTables(obj).then(response => {
          if (response) {
            this.rTbList = response
          }
        })
      }
    },
    getSchema() {
      const obj = {
        datasourceId: this.readerForm.datasourceId
      }
      dsQueryApi.getTableSchema(obj).then(response => {
        this.schemaList = response
      })
    },
    // schema 切换
    schemaChange(e) {
      this.readerForm.tableSchema = e
      // 获取可用表
      this.getTables('rdbmsReader')
    },

    // 表模糊匹配
    fuzzyMatchingTable(e) {
      this.readerForm.fuzzyMatchingTableName = e
      // 获取可用表
      this.getTables('rdbmsReader')
    },
    // reader 数据源切换
    rDsChange(e) {
      // 清空已有数据
      this.resetForm()

      // 设置新的 datasourceId 和 dataSource
      this.readerForm.datasourceId = e
      this.rDsList.find((item) => {
        if (item.id === e) {
          this.dataSource = item.datasource
        }
      })

      Bus.dataSourceId = e
      this.$emit('selectDataSource', this.dataSource)

      if (this.dataSource === 'postgresql' || this.dataSource === 'oracle' || this.dataSource === 'sqlserver') {
        this.getSchema()
      } else {
        this.getTables('rdbmsReader')
      }
    },

    // 获取表字段
    getColumns(type) {
      if (type === 'reader') {
        this.getTableInfo()
      }
    },

    getProcedureColumns() {
      const obj = {
        tableName: this.readerForm.customTableName,
        datasourceId: this.readerForm.datasourceId,
        procedureCall: this.readerForm.procedureCall
      }
      dsQueryApi.getTableInfo(obj).then(response => {
        if (response) {
          this.rColumnList = response.columns
          this.readerForm.columns = response.columns.map(item => item.columnName)
          this.readerForm.checkAll = true
          this.readerForm.isIndeterminate = false
        }
      })
    },

    parseTypeChange(value) {
      this.rColumnList = []
      this.readerForm.columns = []

      if (value === 'table') {
        this.readerForm.customTableName = this.readerForm.tableName
      } else {
        this.readerForm.customTableName = ''
      }
      this.readerForm.tableComment = ''
      this.readerForm.isSetTag = true
      this.readerForm.selectedTags = []

      if (value !== 'table') {
        this.readerForm.tableName = ''
        this.readerForm.fuzzyMatchingTableName = ''
        this.rTbList = []
      }
    },

    // 清空表单数据
    resetForm() {
      this.readerForm = {
        datasourceId: this.readerForm.datasourceId,
        tableName: '',
        columns: [],
        columnsType: [],
        where: '',
        querySql: '',
        checkAll: false,
        isIndeterminate: true,
        splitPk: '',
        tableSchema: '',
        fuzzyMatchingTableName: '',
        parseType: 'table',
        procedureCall: '',
        customTableName: '',
        tableComment: '',
        isSetTag: true,
        selectedTags: []
      }
      this.rColumnList = []
      this.rTbList = []
      this.schemaList = []
    },
    // 表切换
    rTbChange(t) {
      this.readerForm.tableName = t
      if (this.readerForm.parseType === 'table') {
        this.readerForm.customTableName = t
      }
      this.rColumnList = []
      this.readerForm.columns = []
      this.getTableInfo()
    },

    getTableInfo() {
      const obj = {
        datasourceId: this.readerForm.datasourceId,
        tableName: this.readerForm.customTableName,
        querySql: this.readerForm.querySql
      }
      dsQueryApi.getTableInfo(obj).then(response => {
        debugger
        if (response) {
          this.rColumnList = response.columns.map(item => ({
            ...item,
            columnDes: item.columnName
          }))
          this.readerForm.columns = response.columns.map(item => item.columnName)
          this.readerForm.checkAll = true
          this.readerForm.isIndeterminate = false
        }
      })
    },
    rHandleCheckAllChange(val) {
      this.$refs.multipleTable.toggleAllSelection()
      this.readerForm.checkAll = val
      this.readerForm.columns = val ? this.rColumnList.map(item => item.columnName) : []
      this.readerForm.isIndeterminate = false
    },

    rHandleCheckedChange(value) {
      const checkedCount = value.length
      this.readerForm.checkAll = checkedCount === this.rColumnList.length
      this.readerForm.isIndeterminate = checkedCount > 0 && checkedCount < this.rColumnList.length
    },
    getData() {
      if (Bus.dataSourceId) {
        this.readerForm.datasourceId = Bus.dataSourceId
      }
      return {
        readerForm: this.readerForm,
        rColumnList: this.rColumnList
      }
    },
    getTagList() {
      dsQueryApi.getTableTag().then(response => {
        if (response && Array.isArray(response)) {
          this.tagList = response
        } else {
          this.tagList = []
        }
      })
    }

  }
}
</script>

<style scoped>.el-table {
  border: 2px solid #409EFF; /* 外边框 */
  font-size: 14px;
}

.el-table th, .el-table td {
  text-align: left;
  padding: 10px;
}

@media (max-width: 768px) {
  .el-table {
    font-size: 12px;
  }
  .el-table th, .el-table td {
    padding: 6px;
  }
}
</style>
